package youleche.com.common.email;

import java.util.List;

import youleche.com.business.BEmailModule;
import youleche.com.caches.CacheFactory;
import youleche.com.common.ParamConfigParameters;
import youleche.com.model.MEmailConfig;
import youleche.com.model.MEmailModule;
import youleche.com.util.AESEncryptAndDecrypt;

public class MailFactory {
	
	/**
	 * 获取工厂实例
	 * @return
	 */
	public static MailFactory getInstance(){
		return new MailFactory();
	}
	
	/**
	 * 发送邮件
	 * @param registerEmail 注册邮箱
	 * @param random 随机码
	 */
	public String sendMail(String registerEmail, String random){
		MEmailConfig config = this.getEmailConfig(registerEmail);
		if(config != null){
			String smtp = config.getMailServerHost();
			String from = config.getEmail();
			String to = registerEmail;
			String copyto = "";
			String subject = config.getEmailTitle();
			String content = config.getEmailContent();
			content = content.replace("{$email}", registerEmail).replace("{$random}", random);
			String username = config.getEmail();
			String password = config.getUserPassword();
			String filename = "";
			
		    return Mail.sendAndCc(smtp, from, to, copyto, subject, content, username, password, filename) == true ? "ok" : "error"; 
		}
		
		return "error";
	}
	
	/**
	 * 得到发送邮件的配置
	 * @return 邮件的配置
	 */
	@SuppressWarnings("static-access")
	public MEmailConfig getEmailConfig(String registerEmail){
		MEmailConfig config = null;
		try {
			@SuppressWarnings("unchecked")
			List<MEmailConfig> list = (List<MEmailConfig>)CacheFactory.getEmailConfigCache().getCache();
			if(list != null && list.size() > 0){
				for (MEmailConfig fig : list) {
					if("1".equals(fig.getA1())){
						config = fig;
					}
				}
			}
		
			if(config != null){
				//解密
				ParamConfigParameters param = new ParamConfigParameters();
				String key = param.getParameter("EmailPassword_KEY");
				config.setUserPassword(AESEncryptAndDecrypt.decrypt(config.getUserPassword(), key));
				String email = this.getEmailConent();//HtmlHelper.readHtmlContent("").replace("{$email}", registerEmail.split("\\-")[0]).replace("{$random}", registerEmail.split("\\-")[1]);
				System.out.println(email);
				config.setEmailContent(email);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return config;
	}
	
	/**
	 * 得到邮件内容
	 * @return 邮件内容
	 */
	private String getEmailConent(){
		try {
			BEmailModule handler = new BEmailModule();
			MEmailModule module = handler.getEmailModuleByModuleName("邮件模板");
			if(module != null){				
				return module.getModuleContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		return "";
	}
	
	public static void main(String[] args) {
		MailFactory fac = new MailFactory();
		String content = fac.getEmailConent();
		content = content.replace("{$email}", "449614531@qq.com");
		System.out.println(content);
	}
}
